import sys
from random import randint
import pygame
from matplotlib.hatch import Stars
from pygame.sprite import Group
from star import Star
from drop import Drop
import sys

# 13-1 星星：找一幅星星图像，并在屏幕上显示一系列整齐排列的星星。
# 1，完成加载骨架
# 2，创建星星类： 初始化，绘画方法
# 3，创建一群星星： 放在Grop中统一调draw方法。 每个星星位置要计算好（row,col）
# 4，展示
# def show_stars():
#     pygame.init()
#     screen = pygame.display.set_mode((1200, 800))
#     pygame.display.set_caption("展示星星")
#
#     stars = Group()
#     # 13-1
#     # create_stars(stars, screen)
#     # 13-2
#     create_stars2(stars, screen)
#     print("星星数量:", len(stars))
#     # 主循环
#     while True:
#         for event in pygame.event.get():
#             if event.type == pygame.QUIT:
#                 pygame.quit()
#                 sys.exit()
#             elif event.type == pygame.KEYDOWN:
#                 if event.key == pygame.K_q:
#                     pygame.quit()
#                     sys.exit()
#
#         # 绘制
#         screen.fill((230, 230, 230))
#         stars.draw(screen)
#         pygame.display.flip()
#
#
# def create_stars(stars, screen):
#     star = Star(screen)
#     # 计算行
#     row_nums = int((screen.get_rect().height - 3 * star.rect.height) / (star.rect.height * 2))
#     # 计算列
#     col_nums = int((screen.get_rect().width - 2 * star.rect.width) / (star.rect.width * 2))
#     print(str(row_nums) + ":" + str(col_nums))
#     for i in range(row_nums):
#         for j in range(col_nums):
#             star = Star(screen)
#             star_width = star.rect.width
#             star.x = star_width + 2 * star_width * j
#             star.rect.x = star.x
#             star.rect.y = star.rect.height + 2 * star_width * i
#             stars.add(star)


# show_stars()


# 13-2 更逼真的星星：为让星星的分布更逼真，可随机地放置星星。本书前面说过，可像下面这样来生成随机数：
# from random import randint￼ random_number = randint(-10,10)
# 上述代码返回一个-10和10之间的随机整数。在为完成练习13-1而编写的程序中，随机地调整每颗星星的位置。
# print("hello")
# for i in range(10):
#     print(f"第{i}次",randint(-10,10))

# def create_stars2(stars, screen):
#     star = Star(screen)
#     # 计算行
#     row_nums = int((screen.get_rect().height - 3 * star.rect.height) / (star.rect.height * 2))
#     # 计算列
#     col_nums = int((screen.get_rect().width - 2 * star.rect.width) / (star.rect.width * 2))
#     print(str(row_nums) + ":" + str(col_nums))
#     for i in range(row_nums):
#         for j in range(col_nums):
#             star = Star(screen)
#             star_width = star.rect.width
#             star.x = star_width + 2 * star_width * j + randint(-20, 20)
#             star.rect.x = star.x
#             star.rect.y = star.rect.height + 2 * star_width * i + randint(-20, 20)
#             stars.add(star)
#
#
# show_stars()


# 13-3 雨滴：寻找一幅雨滴图像，并创建一系列整齐排列的雨滴。让这些雨滴往下落，直到到达屏幕底端后消失。
# def create_drops(screen, drops):
#     drop = Drop(screen)
#     # 计算行、列
#     available_height = screen.get_rect().height - 4 * drop.rect.height
#     rows = int(available_height / (2 * drop.rect.height))
#
#     available_width = screen.get_rect().width - 2 * drop.rect.width
#     cols = int(available_width / (2 * drop.rect.width))
#
#     for row in range(rows):
#         for col in range(cols):
#             drop = Drop(screen)
#             # print("雨滴速度",drop.speed)
#             drop.rect.x = drop.rect.width + 2 * drop.rect.width * col + randint(-10, 10)
#             drop.rect.y = drop.rect.height + 2 * drop.rect.height * row + randint(-10, 10)
#             drops.add(drop)
#
#
# def show_drops():
#     pygame.init()
#     screen = pygame.display.set_mode((1200, 800))
#     pygame.display.set_caption("雨滴下落")
#
#     drops = Group()
#     create_drops(screen, drops)
#     while True:
#         for event in pygame.event.get():
#             if event.type == pygame.QUIT:
#                 pygame.quit()
#                 sys.exit()
#             elif event.type == pygame.KEYDOWN:
#                 if event.key == pygame.K_q:
#                     pygame.quit()
#                     sys.exit()
#         # 更新雨滴位置
#         drops.update()
#         screen.fill((30, 30, 60))
#         drops.draw(screen)
#         print("雨滴数量",len(drops))
#         # 更新屏幕
#         pygame.display.flip()
#
#
# show_drops()
# 13-4 连绵细雨：修改为完成练习13-3而编写的代码，使得一行雨滴消失在屏幕底端后，屏幕顶端又出现一行新雨滴，并开始往下落。
# 见drop.update

# 13-5 抓球：创建一个游戏，在屏幕底端放置一个玩家可左右移动的角色。让一个球出现在屏幕顶端，且水平位置是随机的，并让这个球以固定的速度往下落。
# 如果角色与球发生碰撞（表示将球抓住了），就让球消失。每当角色抓住球或球因抵达屏幕底端而消失后，都创建一个新球。

from catch_role import CatchRole
from role_ball import RoleBall
from game_stats import GameStats
from settings import Settings


def key_down_event(event, catch_role, role_ball, stats, screen):
    key_name = pygame.key.name(event.key)
    print("KEYDOWN 事件，按键值 event.key =" + str(event.key) + ", 对应的按键名称: " + key_name)
    if event.key == pygame.K_LEFT:
        catch_role.moving_left = True
    elif event.key == pygame.K_RIGHT:
        catch_role.moving_right = True
    elif event.key == pygame.K_c:
        role_ball.change_color()
    elif event.key == pygame.K_RETURN:
        stats.ship_left = 3
        stats.game_active = True

def key_up_event(event, catch_role):
    if event.key == pygame.K_LEFT:
        catch_role.moving_left = False
    elif event.key == pygame.K_RIGHT:
        catch_role.moving_right = False


def check_collision(catch_role, role_ball):
    """检测小球与角色矩形是否碰撞"""
    role_rect = catch_role.rect
    ball_rect = pygame.Rect(
        role_ball.x - role_ball.radius,
        role_ball.y - role_ball.radius,
        2 * role_ball.radius,
        2 * role_ball.radius
    )
    return role_rect.colliderect(ball_rect)


def check_ball_landed(role_ball):
    """检测小球是否落地（底部超出屏幕）"""
    # 小球底部 = 小球y坐标 + 半径，当底部 > 屏幕高度时落地
    return int(role_ball.y) + role_ball.radius > role_ball.screen_rect.height


def catch_ball():
    pygame.init()
    screen = pygame.display.set_mode((1200, 800))
    pygame.display.set_caption("抓球游戏")
    catch_role = CatchRole(screen)
    role_ball = RoleBall(screen, 10)
    ai_settings = Settings()
    stats = GameStats(ai_settings)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                else:
                    key_down_event(event, catch_role, role_ball, stats, screen)
            elif event.type == pygame.KEYUP:
                key_up_event(event, catch_role)
        if stats.game_active:
            # 3. 碰撞检测：碰撞后重置小球
            if check_collision(catch_role, role_ball):
                print("抓住啦！")  # 调试提示（可选删除）
                role_ball = RoleBall(screen, 10)

            # 4. 落地检测：小球落地后重置
            if check_ball_landed(role_ball):
                if stats.ship_left > 0:
                    print("落地啦！")  # 调试提示（可选删除）
                    stats.ship_left -= 1
                    role_ball = RoleBall(screen, 10)
                else:
                    stats.game_active = False
            # 更新屏幕
            screen.fill((230, 230, 240))
            catch_role.update()
            catch_role.draw_catch_role()
            role_ball.draw_role_ball()
            role_ball.update()
            pygame.display.flip()


catch_ball()

# 13-6 游戏结束：在为完成练习13-5而编写的代码中，跟踪玩家有多少次未将球接着。在未接着球的次数到达三次后，结束游戏。
